// utils/http.js

// 导入模块
import Request from 'luch-request'
import { useUserStore } from '@/store/user.js'

//tab页面
const tabBarPage = [
  'pages/my/index',
  'pages/notify/index',
  'pages/wiki/index',
  'pages/index/index'
]
export const baseURL = 'https://consult-api.itheima.net/'
//重定向登录
function reLogin() {
  const currPages = getCurrentPages()[getCurrentPages().length - 1]
  const isTabBar = tabBarPage.includes(currPages.route)
  const returnType = isTabBar ? 'switchTab' : 'navigateTo'
  const useStore = useUserStore()
  useStore.$patch({
    returnUrl: currPages.$page.fullPath,
    returnType,
    token: null,
    refreshToken: null
  })
  uni.redirectTo({
    url: '/pages/login/index'
  })
}
// 实例化网络请求

const http = new Request({
  // 接口基地址
  baseURL,
  custom: {
    loading: true,
    title: '加载中...',
    showToast: true
  }
})
http.interceptors.request.use(
  function (config) {
    if (config.custom.loading) {
      uni.showLoading({
        title: config.custom.title,
        mask: true
      })
    }
    const userStore = useUserStore()
    const defaultHeader = {}
    if (userStore.token)
      defaultHeader.authorization = 'Bearer ' + userStore.token
    config.header = {
      ...defaultHeader,
      ...config.header
    }
    return config
  },
  function (err) {
    uni.hideLoading()
    return Promise.reject(err)
  }
)
http.interceptors.response.use(
  function (res) {
    uni.hideLoading()
    if (res.config.custom.showToast && res.data.code != 10000) {
      uni.utils.toast(res.data.message)
      return Promise.reject(res)
    }
    return res
  },
  function (err) {
    if (err.statusCode === 401) {
      console.log(1)
      reLogin()
    }
    uni.hideLoading()
    return Promise.reject(err)
  }
)
// 导出配置好的模网络模块
export { http }
